package org.example.service;

import org.example.entity.ServiceRequest;
import org.example.repository.ServiceRequestRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 服务申请业务逻辑层
 */
@Service
@Transactional
public class ServiceRequestService {
    
    @Autowired
    private ServiceRequestRepository serviceRequestRepository;
    
    /**
     * 创建服务申请
     */
    public ServiceRequest createServiceRequest(ServiceRequest serviceRequest) {
        // 验证预约时间不能是过去时间
        if (serviceRequest.getAppointmentTime().isBefore(LocalDateTime.now())) {
            throw new RuntimeException("预约时间不能是过去时间");
        }
        
        return serviceRequestRepository.save(serviceRequest);
    }
    
    /**
     * 根据ID获取服务申请
     */
    @Transactional(readOnly = true)
    public Optional<ServiceRequest> findById(Long id) {
        return serviceRequestRepository.findById(id);
    }
    
    /**
     * 获取用户的所有服务申请
     */
    @Transactional(readOnly = true)
    public List<ServiceRequest> findByUserId(Long userId) {
        return serviceRequestRepository.findByUserIdOrderByCreatedAtDesc(userId);
    }
    
    /**
     * 分页获取用户的服务申请
     */
    @Transactional(readOnly = true)
    public Page<ServiceRequest> findByUserId(Long userId, Pageable pageable) {
        return serviceRequestRepository.findByUserIdOrderByCreatedAtDesc(userId, pageable);
    }
    
    /**
     * 获取所有服务申请
     */
    @Transactional(readOnly = true)
    public List<ServiceRequest> findAllServiceRequests() {
        return serviceRequestRepository.findAll();
    }
    
    /**
     * 分页获取所有服务申请
     */
    @Transactional(readOnly = true)
    public Page<ServiceRequest> findAllServiceRequests(Pageable pageable) {
        return serviceRequestRepository.findAll(pageable);
    }
    
    /**
     * 根据状态获取服务申请
     */
    @Transactional(readOnly = true)
    public List<ServiceRequest> findByStatus(String status) {
        return serviceRequestRepository.findByStatusOrderByCreatedAtDesc(status);
    }
    
    /**
     * 根据状态分页获取服务申请
     */
    @Transactional(readOnly = true)
    public Page<ServiceRequest> findByStatus(String status, Pageable pageable) {
        return serviceRequestRepository.findByStatusOrderByCreatedAtDesc(status, pageable);
    }
    
    /**
     * 根据紧急程度获取服务申请
     */
    @Transactional(readOnly = true)
    public List<ServiceRequest> findByUrgencyLevel(String urgencyLevel) {
        return serviceRequestRepository.findByUrgencyLevelOrderByCreatedAtDesc(urgencyLevel);
    }
    
    /**
     * 根据紧急程度分页获取服务申请
     */
    @Transactional(readOnly = true)
    public Page<ServiceRequest> findByUrgencyLevel(String urgencyLevel, Pageable pageable) {
        return serviceRequestRepository.findByUrgencyLevelOrderByCreatedAtDesc(urgencyLevel, pageable);
    }
    
    /**
     * 获取紧急待处理的服务申请
     */
    @Transactional(readOnly = true)
    public List<ServiceRequest> findUrgentPendingRequests() {
        return serviceRequestRepository.findUrgentPendingRequests();
    }
    
    /**
     * 更新服务申请状态
     */
    public ServiceRequest updateStatus(Long id, String status) {
        ServiceRequest serviceRequest = serviceRequestRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("服务申请不存在"));
        
        // 验证状态转换是否合法
        if (!isValidStatusTransition(serviceRequest.getStatus(), status)) {
            throw new RuntimeException("无效的状态转换");
        }
        
        serviceRequest.setStatus(status);
        return serviceRequestRepository.save(serviceRequest);
    }
    
    /**
     * 取消服务申请
     */
    public ServiceRequest cancelServiceRequest(Long id) {
        ServiceRequest serviceRequest = serviceRequestRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("服务申请不存在"));
        
        if (!serviceRequest.canCancel()) {
            throw new RuntimeException("当前状态的服务申请不能取消");
        }
        
        serviceRequest.setStatus("CANCELLED");
        return serviceRequestRepository.save(serviceRequest);
    }
    
    /**
     * 完成服务申请
     */
    public ServiceRequest completeServiceRequest(Long id) {
        ServiceRequest serviceRequest = serviceRequestRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("服务申请不存在"));
        
        if (!serviceRequest.canComplete()) {
            throw new RuntimeException("当前状态的服务申请不能完成");
        }
        
        serviceRequest.setStatus("COMPLETED");
        serviceRequest.setCompletedAt(LocalDateTime.now());
        return serviceRequestRepository.save(serviceRequest);
    }
    
    /**
     * 完成服务申请（指定完成人）
     */
    public ServiceRequest completeServiceRequest(Long id, Long completedBy) {
        ServiceRequest serviceRequest = serviceRequestRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("服务申请不存在"));
        
        if (!serviceRequest.canComplete()) {
            throw new RuntimeException("当前状态的服务申请不能完成");
        }
        
        serviceRequest.setStatus("COMPLETED");
        serviceRequest.setCompletedBy(completedBy);
        serviceRequest.setCompletedAt(LocalDateTime.now());
        return serviceRequestRepository.save(serviceRequest);
    }
    
    /**
     * 删除服务申请
     */
    public void deleteServiceRequest(Long id) {
        if (!serviceRequestRepository.existsById(id)) {
            throw new RuntimeException("服务申请不存在");
        }
        serviceRequestRepository.deleteById(id);
    }
    
    /**
     * 统计用户的服务申请数量
     */
    @Transactional(readOnly = true)
    public long countByUserId(Long userId) {
        return serviceRequestRepository.countByUserId(userId);
    }
    
    /**
     * 统计指定状态的服务申请数量
     */
    @Transactional(readOnly = true)
    public long countByStatus(String status) {
        return serviceRequestRepository.countByStatus(status);
    }
    
    /**
     * 统计指定紧急程度的服务申请数量
     */
    @Transactional(readOnly = true)
    public long countByUrgencyLevel(String urgencyLevel) {
        return serviceRequestRepository.countByUrgencyLevel(urgencyLevel);
    }
    
    /**
     * 获取用户各状态的服务申请统计
     */
    @Transactional(readOnly = true)
    public List<Object[]> getUserServiceRequestStats(Long userId) {
        return serviceRequestRepository.countByUserIdAndStatus(userId);
    }
    
    /**
     * 验证状态转换是否合法
     */
    private boolean isValidStatusTransition(String currentStatus, String newStatus) {
        switch (currentStatus) {
            case "PENDING":
                return "IN_PROGRESS".equals(newStatus) || "CANCELLED".equals(newStatus);
            case "IN_PROGRESS":
                return "COMPLETED".equals(newStatus) || "CANCELLED".equals(newStatus);
            case "COMPLETED":
            case "CANCELLED":
                return false; // 已完成或已取消的状态不能转换
            default:
                return false;
        }
    }
    
}
